package com.javasm.adminapi.login.model;

import com.javasm.adminapi.module.system.dto.MenuTypeDTO;
import com.javasm.adminapi.module.system.entity.Role;
import com.javasm.adminapi.module.system.entity.User;
import com.javasm.adminapi.module.system.service.PermissionService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @className: LoginUser
 * @description:
 * @author: zcx
 * @date: 2025/10/15 11:21
 * @version: 0.1
 * @since: jdk17
 */

public class LoginUser implements UserDetails {
    private User user;

    public LoginUser(User user) {
        this.user = user;
    }
    public User getUser() {
        return user;
    }
    private transient Set<GrantedAuthority> cachedAuthorities;


    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if(cachedAuthorities != null){
            return cachedAuthorities;
        }
        synchronized ( this){
            if (cachedAuthorities != null) {
                return cachedAuthorities;
            }
            List<MenuTypeDTO> urlList = user.getUrlList();

            if (urlList == null) {
                return Collections.emptyList();
            }

            Set<GrantedAuthority> collect = urlList.stream()
                    .map(menu -> {
                        String code = menu.getCode()+":"+menu.getApiType();
                        SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(code);
                        return simpleGrantedAuthority;
                    })
                    .collect(Collectors.toSet());
            cachedAuthorities = collect;
            return cachedAuthorities;
        }
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return user.getStatus() == 1;
    }
}
